//
//  DDMainViewController.m
//  剪切板dome
//
//  Created by chenyuan on 2020/6/18.
//  Copyright © 2020 chenyuan. All rights reserved.
//

#import "DDMainViewController.h"
#import <WebKit/WebKit.h>
#import "WKWebViewJavascriptBridge.h"
#import "DDPlayGameViewController.h"

@interface DDMainViewController ()<WKNavigationDelegate>
@property (nonatomic, strong) WKWebViewJavascriptBridge *bridge;

@property (nonatomic, strong) WKWebView *ddWeview;

@end

@implementation DDMainViewController

#pragma mark - LifeCycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self setupUI];

    [self setupData];
}

- (void)viewWillAppear:(BOOL)animated
{
    [self.navigationController setNavigationBarHidden:YES animated:animated];
}

#pragma mark - setupUI

- (void)setupUI
{
    WKWebViewConfiguration * config = [[WKWebViewConfiguration alloc] init];
    config.allowsInlineMediaPlayback = YES;
    config.mediaTypesRequiringUserActionForPlayback = false;
    
    CGFloat origin_y = 20.0f;
    CGFloat safeHeight = 0.0f;
    if ([DDMainViewController hlf_hasFringeScreen]) {
        origin_y = 44.0f;
        safeHeight = 34.0f;
    }
    WKWebView * ddWeview = [[WKWebView alloc] initWithFrame:CGRectMake(0, origin_y, self.view.frame.size.width, self.view.frame.size.height- origin_y - safeHeight) configuration:config];  // 自已定义frame
    ddWeview.navigationDelegate = self;
    [self.view addSubview:ddWeview];
    self.ddWeview = ddWeview;
}

+ (BOOL)hlf_hasFringeScreen
{
    BOOL isFringeScreen = NO;
    if (UIDevice.currentDevice.userInterfaceIdiom != UIUserInterfaceIdiomPhone) {
        return isFringeScreen;
    }
    if (@available(iOS 11.0, *)) {
        UIWindow *window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
        if (window.safeAreaInsets.bottom > 0.0) {
            isFringeScreen = YES;
        }
    }
    return isFringeScreen;
}

#pragma mark - setupData

- (void)setupData
{
    [WKWebViewJavascriptBridge enableLogging]; // // 开启日志，方便调试
    self.bridge = [WKWebViewJavascriptBridge bridgeForWebView:self.ddWeview]; //给哪个webview建立JS与OjbC的沟通桥梁
    [self.bridge setWebViewDelegate:self];  // 设置代理，如果不需要实现，可以不设置
    [self.ddWeview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.redirectUrl]]];

    // js 交互
    [self.bridge registerHandler:@"GetNegotiate" handler:^(id data, WVJBResponseCallback responseCallback) {
        responseCallback(@{@"touch":@"touch"});
    }];
    
    [self.bridge registerHandler:@"GetDDToken" handler:^(id data, WVJBResponseCallback responseCallback) {
        if (responseCallback) {
            NSString * token = [[NSUserDefaults standardUserDefaults] valueForKey:@"token"];
            NSString * ID = [[NSUserDefaults standardUserDefaults] valueForKey:@"Id"];
            if (ID.length != 0) {
                responseCallback(@{@"id":ID,@"token":token});
            }
        }
    }];
    
    [self.bridge registerHandler:@"GetDDAPPchannel" handler:^(id data, WVJBResponseCallback responseCallback) {
        if (responseCallback) {
            responseCallback(@"AppStore");
        }
    }];
    
    [self.bridge registerHandler:@"SetDDtoken" handler:^(id data, WVJBResponseCallback responseCallback) {
        NSDictionary * dataD = data;
        NSUserDefaults * user = [NSUserDefaults standardUserDefaults];
        [user setValue:dataD[@"id"] forKey:@"Id"];
        [user setValue:dataD[@"token"] forKey:@"token"];
    }];
    
    [self.bridge registerHandler:@"SetDDExitLogin" handler:^(id data, WVJBResponseCallback responseCallback) {
        NSUserDefaults * user = [NSUserDefaults standardUserDefaults];
        [user removeObjectForKey:@"Id"];
        [user removeObjectForKey:@"token"];
    }];
    
    [self.bridge registerHandler:@"SetDDWeixinURL" handler:^(id data, WVJBResponseCallback responseCallback) {
        NSString * url = data;
        NSString *urlStr = [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlStr] options:@{} completionHandler:nil];
    }];
    
    [self.bridge registerHandler:@"SetDDTreasureURL" handler:^(id data, WVJBResponseCallback responseCallback) {
        NSString * url = data;
        NSString *urlStr = [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlStr] options:@{} completionHandler:nil];
    }];
    
    __weak typeof(self) weakself = self;
    [self.bridge registerHandler:@"SetDDUUplay" handler:^(id data, WVJBResponseCallback responseCallback) {
        DDPlayGameViewController *gameVC = [[DDPlayGameViewController alloc] init];
        [gameVC configRedirectUrl:data];
        UINavigationController *navigationVC = [[UINavigationController alloc] initWithRootViewController:gameVC];
        navigationVC.modalPresentationStyle = UIModalPresentationFullScreen;
        [weakself presentViewController:navigationVC animated:YES completion:nil];
    }];
}

@end
